package com.food.user.consumer;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;

import com.food.user.config.AlipayConfig;
import com.food.user.entity.Order;
import com.food.user.service.OrderService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@RocketMQMessageListener(consumerGroup = "payCheck",topic = "pay_check")
public class PayCheckConsumer implements RocketMQListener<String> {
    @Autowired
    private OrderService orderInfoService;
    @Override
    public void onMessage(String s) {
        Order orderInfo = orderInfoService.getById(s);
        if (orderInfo.getOrderState()==5){
            //等于待支付状态就查
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
            //商户订单号，商户网站订单系统中唯一订单号
            String out_trade_no = s ;
            //请二选一设置
            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"}");
            //请求
            String flag="";
            try {
                flag  = alipayClient.execute(alipayRequest).getMsg();
                System.out.println(orderInfo.getOrderNum()+":"+flag);
            } catch (AlipayApiException e) {
                    e.printStackTrace();
            }
            if (flag.equals("Success")){
                //支付成功
                System.out.println("检查支付状态:"+orderInfo.getOrderNum());
                orderInfo.setOrderState(0);
                orderInfoService.updateById(orderInfo);
            }
        }
    }
}
